package util;

import org.apache.commons.io.FileUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import static service.ImageService.COMMON_SUFFIX;
import static service.ImageService.SAVE_PATH;

/**
 * 负责根据路径下载图片到本地
 */
public final class ImageProcessUtil {
	public static String getImageSuffixByUrl(String url) throws RuntimeException {
		int suffixIndex = url.lastIndexOf(".");
		if (suffixIndex == -1) { //没有后缀，应该不会有这种异常吧
			throw new RuntimeException("图片地址爬取失败，没有找到图片后缀");
		}
		return url.substring(suffixIndex + 1);
	}

	public static void imageDownload(String url, String filePath) throws IOException {
		Connection.Response response = Jsoup.connect(url)
				.ignoreContentType(true) //省去contentType
				.execute();

		try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.bodyAsBytes())) {
			FileUtils.copyInputStreamToFile(inputStream,
					new File(filePath));
		}
	}

	/**
	 * 检查本地是否已有该图片
	 *
	 * @param fileName 文件名，注意不加路径，不加后缀
	 * @return 文件全路径，找不到就返回null
	 */
	public static String checkLocalImage(String fileName) {
		String filePath = SAVE_PATH + File.separator + fileName + ".";
		for (String suffix : COMMON_SUFFIX) {
			if (!new File(filePath + suffix).isFile()) continue;
			return filePath + suffix;
		}
		return null;
	}
}
